<template>
  <div class="room-info-container" v-if="visible">
    <div class="room-info-card">
      <div class="room-header">
        <span class="room-icon">🏠</span>
        <span class="room-title">房间信息</span>
        <button class="close-btn" @click="$emit('close')" title="关闭">✕</button>
      </div>
      
      <div class="room-details">
        <div class="room-item"><span class="label">房间名:</span><span class="value">{{ roomName }}</span></div>
        <div class="room-item"><span class="label">玩家数:</span><span class="value">{{ playerCount }}/{{ maxPlayers }}</span></div>
        <div class="room-item"><span class="label">状态:</span><span class="value status" :class="statusClass">{{ statusText }}</span></div>
      </div>
      
      <!-- 玩家列表 -->
      <div class="players-section">
        <h4 class="section-title">玩家列表</h4>
        <div class="players-list">
          <div v-for="player in players" :key="player.id" class="player-item">
            <div class="player-info">
              <span class="player-name">{{ player.name }}</span>
              <span v-if="player.isHost" class="host-badge">👑</span>
            </div>
            <div class="player-status">
              <span :class="['ready-status', player.isReady ? 'ready' : 'not-ready']">
                {{ player.isReady ? '✅ 已准备' : '⏳ 未准备' }}
              </span>
              <button 
                v-if="!player.isHost && player.id !== currentPlayerId" 
                @click="togglePlayerReady(player.id)"
                :class="['ready-btn', player.isReady ? 'unready' : 'ready']"
                :disabled="gameStatus !== 'waiting'"
              >
                {{ player.isReady ? '取消准备' : '准备' }}
              </button>
            </div>
          </div>
        </div>
      </div>
      
      <div class="room-actions">
        <!-- 开始游戏按钮（仅房主可见） -->
        <button 
          v-if="isHost && gameStatus === 'waiting'"
          @click="startGame"
          :disabled="!canStartGame"
          class="action-btn start-btn"
          title="开始游戏"
        >
          🎮 开始游戏
        </button>
        
        <!-- 重置画布按钮（仅房主可见） -->
        <button 
          v-if="isHost && gameStatus === 'finished'"
          @click="resetCanvas"
          class="action-btn reset-btn"
          title="重置画布"
        >
          🔄 重置画布
        </button>
        
        <button class="action-btn leave-btn" @click="$emit('leave-room')" title="离开房间">🚪 离开</button>
      </div>
    </div>
  </div>
</template>

<script>
import { computed } from 'vue'
import { useGameStore } from '@/stores/game'
import { useSocketStore } from '@/stores/socket'
import { ElMessage } from 'element-plus'

export default {
  name: 'RoomInfo',
  props: {
    visible: { type: Boolean, default: true },
    roomId: { type: String, default: '' },
    roomName: { type: String, default: '' },
    playerCount: { type: Number, default: 0 },
    maxPlayers: { type: Number, default: 5 },
    gameStatus: { type: String, default: 'waiting' }
  },
  emits: ['leave-room', 'close'],
  setup(props) {
    const gameStore = useGameStore()
    const socketStore = useSocketStore()
    
    // 计算属性
    const players = computed(() => gameStore.players)
    const currentPlayerId = computed(() => gameStore.currentPlayer)
    const isHost = computed(() => {
      const currentPlayer = players.value.find(p => p.id === currentPlayerId.value)
      return currentPlayer?.isHost || false
    })
    
    const canStartGame = computed(() => {
      return gameStore.canStartGame
    })
    
    // 状态文本映射
    const statusText = computed(() => {
      switch (props.gameStatus) {
        case 'waiting': return '等待中'
        case 'playing': return '游戏中'
        case 'finished': return '已结束'
        default: return '未知'
      }
    })
    
    // 状态样式类
    const statusClass = computed(() => {
      switch (props.gameStatus) {
        case 'waiting': return 'status-waiting'
        case 'playing': return 'status-playing'
        case 'finished': return 'status-finished'
        default: return ''
      }
    })
    
    // 切换玩家准备状态
    const togglePlayerReady = async (playerId) => {
      try {
        const player = players.value.find(p => p.id === playerId)
        if (!player) return
        
        const newReadyState = !player.isReady
        
        // 通过Socket发送准备状态
        if (socketStore && socketStore.isConnected) {
          await socketStore.playerReady({
            roomId: props.roomId,
            playerId: playerId,
            isReady: newReadyState
          })
        }
        
        // 更新本地状态
        gameStore.updatePlayerReady(playerId, newReadyState)
        
        ElMessage.success(`已${newReadyState ? '准备' : '取消准备'}`)
      } catch (error) {
        console.error('切换准备状态失败:', error)
        ElMessage.error('切换准备状态失败')
      }
    }
    
    // 开始游戏
    const startGame = async () => {
      try {
        // 兜底：确保连接与组关系
        try {
          if (!socketStore.isConnected) {
            await socketStore.connect()
          }
          await socketStore.joinRoom({ roomId: props.roomId })
        } catch (_) {}

        // 若房主未准备，自动置为准备
        const host = players.value.find(p => p.isHost)
        if (host && !host.isReady && socketStore && socketStore.isConnected) {
          try {
            await socketStore.setPlayerReady(props.roomId, true)
            gameStore.updatePlayerReady(host.id, true)
          } catch (_) {}
        }

        // 允许由服务端最终校验
        await socketStore.startGame(props.roomId)
        ElMessage.info('开始请求已发送，等待倒计时...')
      } catch (error) {
        console.error('开始游戏失败:', error)
        ElMessage.error('开始游戏失败')
      }
    }
    
    // 重置画布
    const resetCanvas = async () => {
      try {
        if (socketStore && socketStore.isConnected) {
          await socketStore.resetCanvas(props.roomId)
        }
        
        ElMessage.success('画布已重置')
      } catch (error) {
        console.error('重置画布失败:', error)
        ElMessage.error('重置画布失败')
      }
    }
    
    return {
      players,
      currentPlayerId,
      isHost,
      canStartGame,
      statusText,
      statusClass,
      togglePlayerReady,
      startGame,
      resetCanvas
    }
  }
}
</script>

<style scoped>
.room-info-container { position: fixed; top: 20px; right: 20px; z-index: 1000; }
.room-info-card { width: 320px; background: white; border: 1px solid #E5E7EB; border-radius: 12px; box-shadow: 0 8px 20px rgba(0,0,0,0.08); overflow: hidden; }
.room-header { display: flex; align-items: center; justify-content: space-between; padding: 12px 14px; background: #F9FAFB; border-bottom: 1px solid #E5E7EB; }
.room-icon { font-size: 18px; }
.room-title { font-weight: 700; color: #111827; }
.close-btn { background: none; border: none; cursor: pointer; font-size: 16px; color: #6B7280; }
.room-details { padding: 12px 14px; display: flex; flex-direction: column; gap: 8px; }
.room-item { display: flex; align-items: center; justify-content: space-between; }
.label { color: #6B7280; font-size: 13px; }
.value { color: #111827; font-weight: 600; }
.status { padding: 2px 10px; border-radius: 10px; font-size: 12px; }
.status-waiting { background: #FEF3C7; color: #B45309; }
.status-playing { background: #D1FAE5; color: #065F46; }
.status-finished { background: #FEE2E2; color: #991B1B; }
.room-actions { display: flex; gap: 8px; padding: 12px 14px; border-top: 1px solid #E5E7EB; }
.action-btn { flex: 1; padding: 8px 10px; border: 1px solid #E5E7EB; border-radius: 8px; background: white; cursor: pointer; }
.copy-btn:hover { background: #F3F4F6; }
.leave-btn { background: #FEE2E2; border-color: #FCA5A5; }
.leave-btn:hover { background: #FCA5A5; color: white; }

/* New styles for players section */
.players-section { padding: 12px 14px; border-top: 1px solid #E5E7EB; }
.section-title { font-size: 14px; font-weight: 600; color: #374151; margin-bottom: 8px; }
.players-list { display: flex; flex-direction: column; gap: 6px; }
.player-item { display: flex; align-items: center; justify-content: space-between; padding: 6px 0; border-bottom: 1px solid #F3F4F6; }
.player-item:last-child { border-bottom: none; }
.player-info { display: flex; align-items: center; gap: 8px; }
.player-name { font-weight: 600; color: #111827; }
.host-badge { font-size: 14px; color: #D97706; }
.player-status { display: flex; align-items: center; gap: 8px; }
.ready-status { padding: 2px 10px; border-radius: 10px; font-size: 12px; }
.ready-status.ready { background: #D1FAE5; color: #065F46; }
.ready-status.not-ready { background: #FEE2E2; color: #991B1B; }
.ready-btn { padding: 4px 10px; border: 1px solid #E5E7EB; border-radius: 8px; background: white; cursor: pointer; font-size: 12px; }
.ready-btn.ready { background: #D1FAE5; border-color: #065F46; color: #065F46; }
.ready-btn.unready { background: #FEE2E2; border-color: #991B1B; color: #991B1B; }
.ready-btn:hover { background: #F3F4F6; }
.ready-btn:disabled { opacity: 0.6; cursor: not-allowed; }
</style> 